<?php

declare(strict_types=1);

namespace app\service;

use think\facade\Log; // 引入 Log 类

use app\utils\Redis as RedisDB;
class RedisSet
{

    /**
     * Summary of initPermsById
     * 设置permission
     * @param mixed $model
     * @param mixed $id roleId
     * @return \think\response\Json
     */
    public static function initPermsById($model, $id)
    {
        try {
            $pRedis = new RedisDB('perms');
            $role = $model->find($id);
            $perms = $role->menu->column('perms');
            if ($pRedis->exists("perms:roleId:$id")) {
                $pRedis->del("perms:roleId:$id");
            }
            $result = $pRedis->sAdd("perms:roleId:$id", $perms);
            return success("初始化成功", $result);
        } catch (\Throwable $th) {
            return error(" 设置失败$id", $th->getMessage());
        }
    }

    /**
     * Summary of delPermsById
     * 删除permission
     * @param mixed $ids roleId
     * @return \think\response\Json
     */
    public static function delPermsById($ids)
    {
        try {
            $pRedis = new RedisDB('perms');
            foreach ($ids as $id) {
                if ($pRedis->exists("perms:roleId:$id")) {
                    $pRedis->del("perms:roleId:$id");
                }
            }
            return success("删除成功", $ids);
        } catch (\Throwable $th) {
            return error(" 删除失败$ids", $th->getMessage());
        }
    }

    public static function logoutById($model, $uid,$opUid)
    {
        try {
            //code...
            $uRedis = new RedisDB('user');
            $user = $model->where('user_id', $uid)->find();
            $tokenStatus = $uRedis->exists("token:$user->id");
            if ($tokenStatus) {
                $uRedis->del("token:$user->id");
                $uRedis->del("info:$user->id");
                $uRedis->del("role:$user->id");
            }
           $now = $uRedis->hGetAll("info:$opUid");
            Log::channel('sys')->record([
                'content' => "后台修改用户信息，用户强制退出--" . $user->nickname,
                'create_by' =>$now['username'],
                'log_type' => '2',
                'ipaddress' => request()->header('x-real-ip')
            ]);
            return success("退出成功", null);
        } catch (\Throwable $th) {
            //throw $th;
            return error(" 退出失败", $th->getMessage());
        }
    }
}
